<?php

class Bizprofile_Widgets_Mostbuy_Widget extends Tomato_Widget
{
    protected function _prepareShow()
    {
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $lang = $request->getParam('lang');
        $this->_view->assign('lang', $lang);
        $count = 5;

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category models access to data
         */
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);
        
        $infoDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
        $infoDao->setDbConnection($conn);
        $infoDao->setLang($lang);

        $enterprises = $enterpriseDao->getMostBuy($count);

        $arrETS = array();
        $arrInfos = array();
        foreach($enterprises as $enterprise){
            $enterprise_id = $enterprise->id;
            @$$enterprise_id += $enterprise->buy_count;
            $enterprise->buy_count = $$enterprise_id;
            $arrETS[$enterprise->id][0] = $$enterprise_id;
            $arrETS[$enterprise->id][1] = $enterprise;
            
            //Get about us follow enterprise
            $infos = $infoDao->getInfos($enterprise->id, 5);
            $arrInfos[$enterprise->id] = isset($infos[0])?$infos[0]:null;
        }
        array_multisort($arrETS, SORT_DESC);
        $arrESorted = array();
        foreach($arrETS as $row){
            $arrESorted[] = $row[1];
        }
        $this->_view->assign('enterprises', $arrESorted);
        $this->_view->assign('arrInfos', $arrInfos);
    }

    protected function _prepareConfig()
    {

    }
}